"""
Phase 2: Net CA Decomposition
===============================
Replicates and extends extensions CA decomposition:
  Table 1: Z → ca_gdp, trade_balance_gdp, income_balance_gdp
  Table 2: Z → savings-investment decomposition

Output: net_gross/output/tables/net_decomposition*.md
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

OECD = [
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
]

DEMO_VARS = ['Z_1', 'Z_2', 'Z_3']
EBA_CONTROLS = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'log_rel_opw', 'kaopen']


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    return f"{val:.4f}{stars(p)}", f"({se:.4f})"


def run_gls(df, y_var, x_vars, label):
    """Run PanelGLS, return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  SKIP {label}: only {len(sub)} obs")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    gls.fit(y, X, sub['iso3'].values, sub['year'].values)

    result = {
        'model': label, 'dep_var': y_var,
        'n_obs': gls.n_obs, 'n_countries': gls.n_countries,
        'r_squared': gls.r_squared, 'rho': gls.rho,
    }
    for i, name in enumerate(x_vars):
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f}, dep={y_var})")
    for i, name in enumerate(x_vars):
        if name in DEMO_VARS or name in ['old_dep', 'youth_dep']:
            sig = stars(gls.pvalues[i])
            print(f"    {name:25s} {gls.beta[i]:10.4f} ({gls.se[i]:.4f}) {sig}")

    return result


def write_table(results, filename, title, key_vars=None):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    if key_vars is None:
        all_vars = []
        for r in results:
            for k in r:
                if k.endswith('_coef'):
                    vname = k.replace('_coef', '')
                    if vname not in all_vars:
                        all_vars.append(vname)
        key_vars = all_vars

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in key_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    for stat, key, fmt_str in [('N', 'n_obs', '{}'), ('R²', 'r_squared', '{:.4f}'),
                                ('Countries', 'n_countries', '{}')]:
        row = f"| {stat} |"
        for r in results:
            row += f" {fmt_str.format(r[key])} |"
        lines.append(row)

    lines.append("\n*Panel GLS with AR(1) errors. Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


def main():
    print("=" * 70)
    print("PHASE 2: NET CA DECOMPOSITION")
    print("=" * 70)

    df = pd.read_csv(DATA / "net_gross_panel.csv")
    df = df[df['year'] <= 2024].copy()
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")

    controls = [c for c in EBA_CONTROLS if c in df.columns and df[c].notna().sum() > 200]
    base_vars = DEMO_VARS + controls

    # ══════════════════════════════════════════════════════════════════
    # TABLE 1: CA Decomposition — Full + OECD + Pre/Post-GFC
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("TABLE 1: CA DECOMPOSITION")
    print("=" * 50)

    results_t1 = []
    for dep, label_suffix in [('ca_gdp', 'CA/GDP'),
                               ('trade_balance_gdp', 'Trade Bal'),
                               ('income_balance_gdp', 'Income Bal')]:
        if dep not in df.columns:
            print(f"  SKIP: {dep} not in panel")
            continue
        r = run_gls(df, dep, base_vars, f'Full: {label_suffix}')
        if r: results_t1.append(r)

    # OECD subsample
    df_oecd = df[df['iso3'].isin(OECD)].copy()
    for dep, label_suffix in [('ca_gdp', 'CA/GDP'),
                               ('trade_balance_gdp', 'Trade Bal'),
                               ('income_balance_gdp', 'Income Bal')]:
        if dep not in df.columns:
            continue
        r = run_gls(df_oecd, dep, base_vars, f'OECD: {label_suffix}')
        if r: results_t1.append(r)

    write_table(results_t1, "net_decomposition_ca.md",
                "Table 1: CA Decomposition — Trade vs Income Balance",
                key_vars=DEMO_VARS + controls)

    # Pre/post-GFC split
    results_gfc = []
    for period, mask, label in [('Pre-GFC', df['year'] <= 2007, 'Pre-GFC'),
                                 ('Post-GFC', df['year'] >= 2010, 'Post-GFC')]:
        sub = df[mask].copy()
        for dep, dep_label in [('ca_gdp', 'CA'), ('income_balance_gdp', 'Income')]:
            if dep not in df.columns:
                continue
            r = run_gls(sub, dep, base_vars, f'{label}: {dep_label}')
            if r: results_gfc.append(r)

    if results_gfc:
        write_table(results_gfc, "net_decomposition_gfc.md",
                    "Table 1b: CA Decomposition — Pre vs Post-GFC",
                    key_vars=DEMO_VARS)

    # ══════════════════════════════════════════════════════════════════
    # TABLE 2: Savings-Investment Decomposition
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("TABLE 2: SAVINGS-INVESTMENT DECOMPOSITION")
    print("=" * 50)

    results_t2 = []
    si_vars = ['savings_investment_gap', 'gross_national_savings_gdp', 'gross_investment_gdp']
    si_vars = [v for v in si_vars if v in df.columns and df[v].notna().sum() > 200]

    for dep in si_vars:
        r = run_gls(df, dep, base_vars, f'Full: {dep}')
        if r: results_t2.append(r)

    for dep in si_vars:
        r = run_gls(df_oecd, dep, base_vars, f'OECD: {dep}')
        if r: results_t2.append(r)

    if results_t2:
        write_table(results_t2, "net_decomposition_si.md",
                    "Table 2: Savings-Investment Decomposition",
                    key_vars=DEMO_VARS + controls)

    print("\n" + "=" * 70)
    print("PHASE 2 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
